package reportes;

import entidades.Impresora;
import java.awt.Frame;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.MediaSizeName;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporter;
import net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import rn.ConfiguracionRN;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Pablo
 */
public class GenReportes {

    Connection cn;
    Impresora impresora;

    public GenReportes() {
        try {
            Class.forName("org.postgresql.Driver");
            cn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/hormicat_db", "postgres", "root");
            impresora = ConfiguracionRN.getImpresoraXMac(getMacAdreess());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void repVehiculosHormicat() {
        try {
            String file = "C:\\reportesSH\\RepVechiculosHormicatSA.jasper";
            JasperPrint p = JasperFillManager.fillReport(file, null, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Parque automotor - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void repVehiculosExternosAHormicat() {
        try {
            String file = "C:\\reportesSH\\RepVechiculosExtHormicatSA.jasper";
            JasperPrint p = JasperFillManager.fillReport(file, null, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Vehiculos Externos a la empresa");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repTodosVehiculos() {
        try {
            String file = "C:\\reportesSH\\RepTodosVechiculos.jasper";
            JasperPrint p = JasperFillManager.fillReport(file, null, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Vehiculos Externos a la empresa");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void repVehiculosEnObra(String obra) {
        try {
            String file = "C:\\reportesSH\\RepVechiculosEnObra.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("obra_filtro", obra);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Vehiculos por Obra");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repVehiculosPorCategoria(String categoria) {
        try {
            String file = "C:\\reportesSH\\RepVechiculosPorCategoria.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("categoria_filtro", categoria);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Vehiculos por Categoria");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repVehiculosPorPropietario(String pro) {
        try {
            String file = "C:\\reportesSH\\RepVechiculosPorPropietario.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("propietario_filtro", pro);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Vehiculos por Propietario");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repTodosRepuestos() {
        try {
            String file = "C:\\reportesSH\\RepTodosRepuestos.jasper";
            JasperPrint p = JasperFillManager.fillReport(file, null, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Repuestos y Partes - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repRepuestosPorProveedor(String pro) {
        try {
            String file = "C:\\reportesSH\\RepRepuestosPorProveedor.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("proveedor_filtro", pro);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Repuestos y Partes - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repRepuestosPorMarca(String pro) {
        try {
            String file = "C:\\reportesSH\\RepRepuestosPorMarca.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("marca_filtro", pro);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Repuestos y Partes - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repRepuestosPorCategoria(String pro) {
        try {
            String file = "C:\\reportesSH\\RepRepuestosPorCategoria.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("categ_filtro", pro);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Repuestos y Partes - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    //Ingreso Combustible
    public void repIngresoCombustible(Long id) {
        try {
            String file = "C:\\reportesSH\\RepIngresoCombustible.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("id_carga", id);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Ingreso de combustible - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    //Salida Combustible
    public void repSalidaCombustible(Long id) {
        try {
            String file = "C:\\reportesSH\\repSalidaCombustible.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("id_parametro", id);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Salida de combustible - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repSalidaCombustibleXTanqueDiscriminado(Long id) {
        try {
            String file = "C:\\reportesSH\\repHistoriaSalidaCombustibleXTanqueDiscriminado.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("tanque_id", id);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Salida de combustible por Tanque - Hormicat S.A.");
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            ////imprimir(p);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repSalidaCombustibleXTanqueDiscriminadoForFecha(Date inicio, Date fin) {
        try {
            String file = "C:\\reportesSH\\repHistoriaSalidaCombustibleXTanqueDiscriminadoPorFecha.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("fecha_inicio", inicio);
            parametros.put("fecha_fin", fin);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Salida de combustible por Tanque - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repSalidaCombustibleXVehiculoDiscriminadoForFecha(Date inicio, Date fin, Long id_vehiculo, Long id_tanque) {
        try {
            String file = "C:\\reportesSH\\repHistoriaSalidaCombustibleXVehiculoDiscriminadoPor.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("fecha_inicio", inicio);
            parametros.put("fecha_fin", fin);
            parametros.put("vehiculo_id", id_vehiculo);
            parametros.put("tanque_id", id_tanque);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Salida de combustible por Tanque - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repSalidaCombustibleXVehiculoDiscriminadoCompleto(Long id_vehiculo, Long id_tanque) {
        try {
            String file = "C:\\reportesSH\\repHistoriaSalidaCombustibleXVehiculoDiscriminadoCompleto.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("vehiculo_id", id_vehiculo);
            parametros.put("tanque_id", id_tanque);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Salida de combustible por Tanque - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repHistorialIngresoRepuestoXDepositoDiscriminado(Long id_deposito) {
        try {
            String file = "C:\\reportesSH\\repHistorialIngresoRepuestos.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("id_deposito", id_deposito);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Historial de Ingreso de Repuestos - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repHistorialIngresoRepuestoXDepositoYFechaDiscriminado(Long id_deposito, Date inicio, Date fin) {
        try {
            String file = "C:\\reportesSH\\repHistorialIngresoRepuestosPorFecha.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("id_deposito", id_deposito);
            parametros.put("fecha_inicio", inicio);
            parametros.put("fecha_fin", fin);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Historial de Ingreso de Repuestos - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repIngresoRepuesto(Long id_lote) {
        try {
            String file = "C:\\reportesSH\\repIngresoRepuestos.jasper";
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("ingreso_id", id_lote);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Ingreso de Repuestos - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    public void repCambioDeRepuestoXLote(Long id_lote) {
        try {
            String file = "C:\\reportesSH\\repCambioDeRepuesto.jasper";        
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("nro_lote", id_lote);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Reporte de cambio de repuestos - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    
    public void repCambioDeRepuestoTodos(Long id_vehiculo) {
        try {
            Map<String, Object> parametros = new HashMap<String, Object>();
            String file = "C:\\reportesSH\\repCambioDeRepuestosTodos.jasper";
            if(id_vehiculo != null){
                file = "C:\\reportesSH\\repCambioDeRepuestosTodosXVehiculo.jasper";
                parametros.put("vehiculo_id", id_vehiculo);
            }                        
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Reporte de cambio de repuestos - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
     public void repHistorialCambioRepuestoXFecha(Long id_vehiculo, Date inicio, Date fin) {
        try {
            String file = "C:\\reportesSH\\repCambioDeRepuestosPorFecha.jasper";
            if(id_vehiculo != null){
                file = "C:\\reportesSH\\repCambioDeRepuestosPorFechaXVehiculo.jasper";                
            }            
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("vehiculo_id", id_vehiculo);
            parametros.put("fecha_inicio", inicio);
            parametros.put("fecha_fin", fin);
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Historial de Ingreso de Repuestos - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }   
     
    public void repHistorialCambioRepuestoDeRuedasXVehiculo(Long id_vehiculo, int rueda, int eje) {
        try {
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("vehiculo_id", id_vehiculo);
            String file = "C:\\reportesSH\\repCambiodeRepuestoEnRuedasXVehiculo.jasper";
            if(rueda != 0 & eje !=0){
                file = "C:\\reportesSH\\repCambiodeRepuestoEnRuedasXVehiculoXRueda.jasper";
                parametros.put("rueda", rueda);
                parametros.put("eje", eje);
            }                                    
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Historial de Ingreso de Repuestos - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }    
    
    public void repIngresoRepuestosXIdLote(Long id_lote) {
        try {
            
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("ingreso_id", id_lote);
            String file = "C:\\reportesSH\\repIngresoMateriales.jasper";            
            JasperPrint p = JasperFillManager.fillReport(file, parametros, cn);            
            JasperViewer view = new JasperViewer(p, false);
            view.setTitle("Ingreso de materiales - Hormicat S.A.");            
            view.setExtendedState(Frame.MAXIMIZED_BOTH);
            view.setVisible(true);
            //imprimir(p);
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
    
    private void imprimir(JasperPrint p) throws PrinterException, JRException {
        PrinterJob job = PrinterJob.getPrinterJob();
        /* Create an array of PrintServices */
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        int selectedService = 0;
        String printer_name = "";
        boolean printer_found = false;
        /* Scan found services to see if anyone suits our needs */
        if(impresora == null) //Si no se seteo ninguna impresora, por defecto se toma la primera encontrada.
            printer_name = services[0].getName().toUpperCase();        
        else
            printer_name = impresora.getDefault_printer();
        
        for (int i = 0; i < services.length; i++) {
            if (services[i].getName().toUpperCase().contains(printer_name)) {
                /*If the service is named as what we are querying we select it */
                printer_found = true;
                selectedService = i;            
            }            
            System.out.println("Impresora: " + services[i].getName().toUpperCase());            
        }
        if(!printer_found)
            job.setPrintService(services[0]);
        job.setPrintService(services[selectedService]);        
        PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
        MediaSizeName mediaSizeName = MediaSize.findMedia(4, 4, MediaPrintableArea.INCH);
        printRequestAttributeSet.add(mediaSizeName);
        printRequestAttributeSet.add(new Copies(1));
        JRPrintServiceExporter exporter = new JRPrintServiceExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, p);
        /* We set the selected service and pass it as a paramenter */
        exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, services[selectedService]);
        exporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET, services[selectedService].getAttributes());
        exporter.setParameter(JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET, printRequestAttributeSet);
        exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.FALSE);        
        exporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.TRUE);        
        exporter.exportReport();
    }
    
    private String getMacAdreess() {
        String macc = "";
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            System.out.println(sb.toString());
            macc = sb.toString();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return macc;
    }
   
}
